package com.muse.appManage.service;

import com.google.common.collect.ImmutableMap;
import com.muse.app.dao.UserDao;
import com.muse.constant.Constant;
import com.muse.constant.ManageRole;
import com.muse.constant.RedisKey;
import com.muse.constant.Role;
import com.muse.entity.Result;
import com.muse.entity.UserInfo;
import com.muse.interceptor.CurrentContext;
import com.muse.model.*;
import com.muse.sqlutils.And;
import com.muse.sqlutils.SqlBuilder;
import com.muse.utils.DigestUtils;
import com.muse.utils.ObjectCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.util.*;

import static com.muse.sqlutils.SqlBuilder.*;

/**
 * Created with IntelliJ IDEA.
 * User: lee
 * Date: 2021/4/25
 * Time: 8:43 下午
 * Description:
 */
@Service
@Slf4j
public class ManageUserService {

    @Autowired
    private UserDao userDao;


    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Result<UserInfoVo> login(LoginParam param) {
        UserInfo userInfo = userDao.getUserInfoByPhone(param.getPhone());
        if (userInfo == null) {
            log.info("ManageUser login userInfo is null,phone={}", param.getPhone());
            return Result.failure("用户不存在", null);
        }
        if (!userInfo.getPassword().equals(DigestUtils.encryptPwd(param.getPassword()))) {
            log.info("ManageUser login userInfo is failure,phone={}", param.getPhone());
            return Result.failure("密码错误", null);
        }
        UserInfoVo vo = convertUserInfoVo(userInfo);
        String token = UUID.randomUUID().toString();
        vo.setToken(Constant.MANAGE_TOKEN + token);
        redisTemplate.opsForValue().set(RedisKey.TOKEN + Constant.MANAGE_TOKEN + token, String.valueOf(vo.getId()));
        return Result.success(vo);
    }

    public Result updatePwd(UpdatePwdParam param) {
        UserInfo userInfo = CurrentContext.get();
        if (!userInfo.getPassword().equals(DigestUtils.encryptPwd(param.getOldPwd()))) {
            log.warn("Manage updatePwd fail oldPwd not same,phone={}", userInfo.getPhone());
            return Result.failure("旧密码不相同,修改失败");
        }
        SqlBuilder.update("t_user", ImmutableMap.of("password", DigestUtils.encryptPwd(param.getNewPwd())))
                .where(
                        eq("id", userInfo.getId())
                ).execute(jdbcTemplate);
        return Result.success();
    }

    public Result out(String token) {
        try {
            redisTemplate.delete(RedisKey.TOKEN + token);
            return Result.success();
        } catch (Exception e) {
            log.error("manage login out error", e);
            return Result.failure();
        }
    }

    public Result<List<UserInfoVo>> list(ManageUserListParam param, Integer page, Integer pageSize) {
        List<UserInfoVo> vos = new ArrayList<>();
        And and = new And();
        and.add(eq("1", 1));
        if (!StringUtils.isEmpty(param.getKeyWord())) {
            and.add(
                    or(
                            likeAll("user_name", param.getKeyWord()),
                            likeAll("phone", param.getKeyWord())
                    )
            );
        }
        if (param.getAppRole() != null) {
            and.add(eq("role", param.getAppRole()));
        }
        if (param.getManageRole() != null) {
            and.add(eq("manage_role", param.getManageRole()));
        }
        long total = select("t_user").where(and).queryForCount(jdbcTemplate);
        List<UserInfo> userInfos = select("t_user").where(and)
                .order("create_time desc")
                .limit((page - 1) * pageSize, pageSize)
                .queryForList(jdbcTemplate, UserInfo.class);
        userInfos.forEach(u -> {
            UserInfoVo vo = convertUserInfoVo(u);
            vos.add(vo);
        });
        return Result.success(vos).pagination(new Result.Pagination(page, pageSize, (int) total));
    }

    public UserInfoVo convertUserInfoVo(UserInfo userInfo) {
        UserInfoVo vo = new UserInfoVo();
        ObjectCopy.copy(userInfo, vo);
        vo.setRoleName(Role.getRoleByValue(vo.getRole()).getName());
        vo.setManageRoleName(ManageRole.getManageRoleByValue(vo.getManageRole()).getName());
        return vo;
    }

    public Result authRole(AuthRoleParam param) {
        UserInfo userInfo = userDao.getUserInfoById(param.getId());
        if (userInfo == null) {
            return Result.failure("用户不存在");
        }
        Map<String, Object> updateParam = new HashMap<>(3);
        updateParam.put("role", param.getAppRole());
        updateParam.put("manage_role", param.getManageRole());
        if (userInfo.getPassword() == null &&
                (param.getManageRole() == ManageRole.LECTURER.getValue() || param.getManageRole() == ManageRole.ADMIN.getValue())) {
            updateParam.put("password", DigestUtils.encryptPwd(Constant.DEFAULT_PASSWORD));
        }
        update("t_user", updateParam).where(eq("id", param.getId())).execute(jdbcTemplate);
        return Result.success();
    }

    public Result<UserInfoVo> me(Integer id) {
        UserInfo userInfo = userDao.getUserInfoById(id);
        return Result.success(convertUserInfoVo(userInfo));
    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.encryptPwd("123456"));
    }
}
